ESX = nil 
local Playerjob = nil 
local PlayerData = nil
local joblabel = nil
local jobgradelabel = nil
local jobgrade = nil
Citizen.Wait(10)
local debug = false
local menu = nil
local vehicles = {}
local vehiclecount = 0
local submenu = {}
local submenubutton = {}
local buttons = {}
local count = 0
local inmenu = false
tables ={
    'airbus',
    'boeing',
    'china',
    'ground_cars',
    'movie',
    'other',
    'russia',
    'other2',
    'russia2',
    'usa',
    'smallplane',
    'train',
    'helicopter',
    'ww2'
}
tableslabels = {
    '空客',
    '波音',
    '中国战斗机',
    '地面车辆',
    '电影游戏',
    '其他',
    '俄罗斯客货机',
    '其他战斗机等',
    '俄罗斯战斗机',
    '美系战斗机',
    '小型飞机',
    '训练用飞机&原版飞机',
    '直升机',
    '二战飞机'
}
TriggerEvent('esx:getSharedObject', function(obj) ESX = obj end)

Citizen.CreateThread(function()
    while true do
        if ESX.IsPlayerLoaded() then
            -- 通过ESX检查玩家职业
            PlayerData = ESX.GetPlayerData()
            if debug then
                for k,v in pairs(PlayerData) do
                    if type (v) == "table" then
                        for k1,v1 in pairs(v) do
                            print (k,k1,v1)
                        end
                    else
                        print (k,v)
                    end
                end
            end
            Playerjob = PlayerData.job.name
            joblabel = PlayerData.job.label
            jobgradelabel = PlayerData.job.grade_label
            jobgrade = PlayerData.job.grade
            -- print (Playerjob)
            menu = MenuV:CreateMenu('刷飞机菜单', '您的职业：' .. joblabel .. '-' .. jobgradelabel , 'topleft', 255, 182, 193, 'size-125', 'native', 'menuv', 'spawn_plane')
            -- menu:OpenWith('KEYBOARD', 'F6')
            menu:On('close', function ()
                -- print ('close')
                MenuV:CloseAll()
                for k,v in pairs(submenu) do
                    v:ClearItems()
                end
                menu:ClearItems()
                --销毁变量
                submenu = {}
                submenubutton = {}
                buttons = {}
                inmenu = false
            end)
            
            break
        end
        Citizen.Wait(10)
    end
end)

RegisterCommand('spawnplane', function()
    if not inmenu then
        TriggerServerEvent ('spawn_plane:load', Playerjob, GetPlayerServerId(PlayerId()),jobgrade)
        inmenu = true
    end
end,false)

RegisterKeyMapping('spawnplane', '刷飞机菜单', 'keyboard', 'F6')

RegisterNetEvent('spawn_plane:load')
AddEventHandler('spawn_plane:load', function(planes)
    -- planes为3层table
    -- 根据planes生成菜单
    -- print (json.encode(planes))
    for k,v in pairs(planes) do
        -- print (k,v)
        submenu[k] = MenuV:CreateMenu( tableslabels[k] , '您现在已经生成' .. vehiclecount .. '架飞机' , 'topleft', 255, 182, 193, 'size-125', 'native', 'menuv')
        submenubutton[k] = menu:AddButton({ icon = '🛩️', label = tableslabels[k] , value = submenu[k],description = '按退格键关闭'})
        for k1,v1 in pairs(v) do
            -- print (k1,v1,v1.label)
            buttons[count]= submenu[k]:AddButton({ icon = '🛩️', label = v1.label ,description = '按退格键关闭' ,select = function ()
                --一个玩家最多在游戏中拥有5架飞机，检查
                if vehiclecount >= 5 then
                    ESX.ShowNotification('您已经生成了5架飞机，若再生成，前序飞机将被销毁')

                    
                    Citizen.Wait(0)
                    while true do 
                        Citizen.Wait(0)
                        ESX.ShowHelpNotification('按~INPUT_PICKUP~键继续生成,按~INPUT_DETONATE~键取消')
                        if IsControlJustReleased(0, 51) then
                            -- print ('51')
                            -- 销毁飞机
                            -- 找到最早生成的飞机。遍历vehicles
                            local oldest = nil
                            local oldestcount = 0
                            k = 0 ; v = 0
                            for k,v in pairs(vehicles) do
                                -- print ("K" .. k .. "V" .. v)
                                if DoesEntityExist(v) then
                                    oldest = v
                                    oldestcount = k
                                    -- print ('oldest' .. oldest .. " " ..oldestcount .. "FINAL")
                                    break
                                end
                            end
                            if oldest ~= nil then
                                -- print ('oldest' .. oldest)
                                ESX.Game.DeleteVehicle(oldest)
                                ESX.ShowNotification('销毁了一架飞机')
                                vehiclecount = vehiclecount - 1
                                vehicles[oldestcount] = nil
                                break
                            end
                        elseif IsControlJustReleased(0, 47) then
                            ESX.ShowNotification('取消生成')
                            menu:Close()
                            MenuV:CloseAll()
                            for k,v in pairs(submenu) do
                                v:ClearItems()
                            end
                            menu:ClearItems()
                            --销毁变量
                            submenu = {}
                            submenubutton = {}
                            buttons = {}
                            inmenu = false
                            return
                        end
                    end
                end

                -- 生成飞机
                menu:Close()
                MenuV:CloseAll()
                for k,v in pairs(submenu) do
                    v:ClearItems()
                end
                menu:ClearItems()
                --销毁变量
                submenu = {}
                submenubutton = {}
                buttons = {}
                -- 得到玩家朝向
                local heading = GetEntityHeading(PlayerPedId())
                ESX.Game.SpawnVehicle(v1.name , GetEntityCoords(PlayerPedId()),  heading ,function (vehicle)
                    ESX.ShowNotification('生成 ' .. v1.label .. ' 成功')
                    --让玩家进入飞机
                    TaskWarpPedIntoVehicle(PlayerPedId(), vehicle, -1)
                    vehiclecount = vehiclecount + 1
                    -- 找vehicles中第一个空的位置
                    -- local empty = 0
                    -- for k,v in pairs(vehicles) do
                    --     if not DoesEntityExist(v) then
                    --         empty = k
                    --         print ('empty' .. empty)
                    --         break
                    --     end
                    -- end
                    -- 插入vehicles
                    
                    vehicles[count+1] = vehicle
                    -- print ('vehicles' .. count+1 .. '=' .. vehicle)
                    inmenu = false
                    count = count + 1
                    return
                end)
            end})
            
        end
    end
    menu:Open()
end)

Citizen.CreateThread(function ()
    while true do
        Citizen.Wait(10)
        -- print (vehiclecount)
        -- 检测vehicles的载具是否存在，不存在则删除数组中的数据
        for k,v in pairs(vehicles) do
            -- print (k,v)
            if not DoesEntityExist(v) and v ~= nil then
                -- print ('vehicle not exist')
                vehicles[k] = nil
                vehiclecount = vehiclecount - 1
            end
        end
    end
end)
